package com.example.element.module.ipc.services;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.common.utils.L;

import static com.example.element.module.ipc.Constants.MSG_FROM_CLIENT;
import static com.example.element.module.ipc.Constants.MSG_FROM_SERVICE;
import static com.example.element.module.ipc.Constants.MSG_KEY;

public class MessengerService extends Service {

    public static final String TAG = MessengerService.class.getSimpleName();



    private Messenger mMessenger = new Messenger(new MessengerHandler());

    private class MessengerHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case MSG_FROM_CLIENT:
                    L.e(TAG, "receive msg from client msg =[" + msg.getData().getString(MSG_KEY) + "]");
                    Messenger client = msg.replyTo;
                    Message relyMsg = Message.obtain(null, MSG_FROM_SERVICE);
                    Bundle bundle = new Bundle();
                    bundle.putString(MSG_KEY, "I have received your message and will reply to you later");
                    relyMsg.setData(bundle);
                    try {
                        client.send(relyMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

}
